import React, { useState, useEffect } from 'react';
import { View, Text, Pressable, Image, FlatList, StyleSheet } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
const MyPost = () => {
    const navigation = useNavigation();
    const [hotPosts, setHotPosts] = useState([]);
    const [historyPosts, setHistoryPosts] = useState([]);
    const [view, setView] = useState([]);
    const [historyView, setHistoryView] = useState([]);
    const [refreshing, isRefresh] = useState(true);
    const [userInfo, setUserInfo] = useState({});
    // const handleRefresh = () => {
    //     isRefresh(true);
    //     getHotPost();
    // }
    const getMyPost = () => {
        axios.get('http://47.111.227.58:3000/dynamic/getdynamicByUser',{
            params: {
                username: userInfo.username
            }
        })
            .then(res => {
                // console.log(res.data);
                setHotPosts(res.data.results);
                const initialView = res.data.results.map(item => item.view);
                setView(initialView)
            })
            .catch(error => {
                console.error(error);
            });
    }
    // const getHistoryPost = () => {
    //     axios.get('http://47.111.227.58:3000/dynamic/getHistoryDynamicView')
    //         .then(res => {
    //             // console.log(res.data);
    //             setHistoryPosts(res.data.results);
    //             const initialView = res.data.results.map(item => item.view);
    //             setHistoryView(initialView)
    //         })
    //         .catch(error => {
    //             console.error(error);
    //         });
    // }
    const handlePostClick = (postId, index) => {
        navigation.navigate('PostDetail', { postId: postId });
        let newView = [...view];
        newView[index] = Number(newView[index]) + 1;
        setView(newView);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicView', {
            data: {
                id: postId,
                view: newView[index]
            }
        }).then(res => {
            console.log(res.data);
        });
    };
    const handleHistoryPostClick = (postId, index) => {
        navigation.navigate('PostDetail', { postId: postId });
        let newView = [...historyView];
        newView[index] = Number(newView[index]) + 1;
        setView(newView);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicView', {
            data: {
                id: postId,
                view: newView[index]
            }
        }).then(res => {
            console.log(res.data);
        });
    };
    useEffect(() => {
        (async () => {
            isRefresh(true);
            const userinfo = await AsyncStorage.getItem('userInfo');
            if (userinfo) {
                setUserInfo(JSON.parse(userinfo))
            }
        })();
    }, []);
    useEffect(() => {
        if (userInfo.username) {
            getMyPost();
        }
    }, [userInfo]);

    const renderPost = ({ item, index }) => {
        const formattedIndex = (index + 1).toString().padStart(2, '0');
        return (
            <Pressable
                style={styles.postItem}
                onPress={() => handlePostClick(item.id, index)}
            >
                <View style={styles.postContent}>
                    <View style={styles.postDetail}>
                        {/* <View style={styles.postIndexContainer}>
                            <Text style={styles.postIndex}>{formattedIndex}</Text>
                        </View> */}
                        <Text style={styles.postStats}>
                            {item.comments} 评论 {item.likes} 点赞 {item.view} 阅读
                        </Text>
                    </View>
                    <Text style={styles.postTitle}>{item.desc}</Text>
                    <View style={styles.userDetail}>
                        <Image style={styles.userAvatar} source={{ uri: item.userImg }} />
                        <Text style={styles.username}>{item.username}</Text>
                        <Text style={styles.boardText}>#{item.board}</Text>
                    </View>
                </View>
                {item.imgUrl && (
                    <Image style={styles.postImage} source={{ uri: item.imgUrl }} />
                )}
            </Pressable>
        );
    };

    return (
        <View style={styles.container}>
            {/* Tab栏 */}
            {/* <View style={styles.tabBar}>
                {['校内十大', '热门板块', '历史热帖'].map(tab => (
                    <Pressable
                        key={tab}
                        style={[styles.tabItem, selectedTab === tab && styles.tabItemSelected]}
                        onPress={() => setSelectedTab(tab)}
                    >
                        <Text style={styles.tabText}>{tab}</Text>
                    </Pressable>
                ))}
            </View> */}

            {/* 帖子列表 */}
            <FlatList
                data={hotPosts}
                renderItem={renderPost}
                keyExtractor={item => item.id}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    tabBar: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: '#fff',
        boxShadow: '0px 2px 2px rgba(0, 0, 0, 0.1)',
        elevation: 3,
    },
    tabItem: {
        alignItems: 'center',
        justifyContent: 'center',
        padding: 10,
    },
    tabItemSelected: {
        borderBottomWidth: 2,
        borderBottomColor: '#EB7A76',
    },
    tabText: {
        fontSize: 16,
        color: '#333',
    },
    postItem: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        backgroundColor: '#fff',
        padding: 10,
        marginVertical: 5,
    },
    postContent: {
        flex: 1,
    },
    postDetail: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    postIndexContainer: {
        backgroundColor: '#f7ca64',
        paddingHorizontal: 6,
        paddingVertical: 2,
        borderRadius: 4,
        marginRight: 10,
    },
    postIndex: {
        fontWeight: 'bold',
        color: '#fff',
    },
    postPlateIndexContainer: {
        backgroundColor: '#f7ca64',
        paddingHorizontal: 2,
        paddingVertical: 0,
        borderRadius: 4,
        position: 'absolute',
        top: 2,
        left: -1,
        // marginRight: 10,
    },
    postPlateIndex: {
        fontWeight: 'bold',
        color: '#fff',
    },
    postStats: {
        fontSize: 14,
        color: '#666',
    },
    postTitle: {
        fontSize: 17,
        color: 'black',
        marginTop: 8,
    },
    postImage: {
        width: 80,
        height: 80,
        borderRadius: 4,
        marginLeft: 10,
    },
    userDetail: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 8,
    },
    userAvatar: {
        width: 20,
        height: 20,
        borderRadius: 10,
        marginRight: 8,
    },
    username: {
        fontSize: 14,
        color: '#333',
    },
    boardText: {
        height: 25,
        width: 55,
        backgroundColor: '#DDE1EA',
        color: '#576B94',
        marginBottom: 5,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 10,
        marginLeft: 'auto',
        marginRight: 5,
        // fontWeight: 'bold',
    },
    plateContent: {
        flexDirection: 'row',
        backgroundColor: '#fff',
        marginBottom: 5,
        height: 65,
    },
    plateContentLeft: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        paddingLeft: 10,
        paddingRight: 10,
    },
    plateContentRight: {
        flexDirection: 'column',
        display: 'flex',
        justifyContent: 'center',
        // alignItems: 'center',
    },
    plateContentText1: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#222222',
        marginBottom: 5,
    },
    plateContentText2: {
        fontSize: 12,
        color: '#999999'
    }
});

export default MyPost;
